package com.live555.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.live555.R;
import com.live555.callback.IH264StoreFinishCallBack;
import com.live555.config.Constants;
import com.live555.rtsp.RTSPClient;
import com.live555.rtsp.RTSPVideoListener;
import com.live555.sava264.H264FileStorePresenter;
import com.live555.screenshot.ScreenShotActivity;
import com.live555.utils.DataConversionUtils;
import com.live555.utils.FileTools;
import com.live555.utils.VideoUtils;
import com.umeng.analytics.MobclickAgent;

/**
 * 功能描述：
 *
 * @author：ZC 创建时间：2018/6/26 10:02
 * 最后修改日期：
 */
public class MainActivity extends Activity implements View.OnClickListener {

    private Context mContext;
    private VideoThread videoThread;
    private SurfaceView sfv;
    private static String RTSP_ADRSS = "rtsp://192.168.1.235/stream";
    private LinearLayout linearLayout;
    /**
     * 拍照
     */
    private ImageView image_take_photo;
    /**
     * 录像
     */
    private ImageView image_recording;
    private int recordFlag = 0;

    public ImageView image;
    /**
     * 录像时间
     */
    private Chronometer recordTime;
    /**
     * 存储H264文件
     */
    private H264FileStorePresenter h264FileStorePresenter;
    /**
     * 本地录像的H264文件名字
     */
    private String localH264FileName = "test.h264";

    static {
        try {
            System.loadLibrary("rtsplive555");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * SD卡读写权限动态申请
     */
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    public static MainActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        /**写死横屏*/
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        }
        setContentView(R.layout.activity_main);
        mContext = this;
        instance = this;

        sfv = (SurfaceView) findViewById(R.id.sfv);
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
        image_take_photo = (ImageView) findViewById(R.id.image_take_photo);
        image_take_photo.setOnClickListener(this);
        image_recording = (ImageView) findViewById(R.id.image_recording);
        image_recording.setOnClickListener(this);
        recordTime = (Chronometer) findViewById(R.id.chronometer);
        image = (ImageView) findViewById(R.id.image);
        VideoUtils.LocalShow.addView(sfv);

        RTSPVideoListener videoListener = new RTSPVideoListener() {
            @Override
            public void videoCallBack(byte[] data, int len) {
                VideoUtils.makeSpsPps(data);
            }
        };
        RTSPClient.setRTSPVideoListener(videoListener);

        if (!TextUtils.isEmpty(RTSP_ADRSS)) {
            videoThread = new VideoThread(RTSP_ADRSS);
            videoThread.start();
        }
        h264FileStorePresenter = new H264FileStorePresenter(ih264StoreFinishCallBack);
        verifyStoragePermissions(this);
    }

    public static void verifyStoragePermissions(Activity activity) {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_take_photo:
                shootSound();
                Intent intent = new Intent(this, ScreenShotActivity.class);
                startActivityForResult(intent, Constants.START_CODE);
                linearLayout.setVisibility(View.INVISIBLE);
                break;
            case R.id.image_recording:
                if (recordFlag == 0) {
                    image_recording.setImageResource(R.drawable.btn_shexianging_1);
                    recordTime.setVisibility(View.VISIBLE);
                    //复位
                    recordTime.setBase(SystemClock.elapsedRealtime());
                    recordTime.start();// 开始计时
                    //开启本地录像
                    h264FileStorePresenter.startStoreH264();
                    localH264FileName = DataConversionUtils.getCurrentDataStr();
                    saveH264ToLocal(true, FileTools.getVideoDir() + localH264FileName + ".h264");
                    recordFlag = 1;
                } else {
                    image_recording.setImageResource(R.drawable.btn_shexiang_1);
                    recordTime.setVisibility(View.INVISIBLE);
                    recordTime.stop();// 停止计时
                    //复位
                    recordTime.setBase(SystemClock.elapsedRealtime());
                    //结束本地录像
                    saveH264ToLocal(false, FileTools.getVideoDir() + localH264FileName + ".h264");
                    h264FileStorePresenter.stopStoreH264();
                    recordFlag = 0;
                }
                break;
            default:
                break;
        }
    }

    /**
     * * 是否保存H264文件到本地
     *
     * @param isToSaveH264
     * @param currentFilePath
     */
    public void saveH264ToLocal(boolean isToSaveH264, String currentFilePath) {
        VideoUtils.isToSaveH264 = isToSaveH264;
        VideoUtils.h264CurrentFilePath = currentFilePath;
    }

    /**
     * 处理完毕回调
     */
    private IH264StoreFinishCallBack ih264StoreFinishCallBack = new IH264StoreFinishCallBack() {
        @Override
        public void onStoreAndParseFinished(boolean result, String msgStr) {
            if (result) {
//                disMissIosLoading();
            }
        }
    };

    private static class VideoThread extends Thread {

        private String url;

        public VideoThread(String path) {
            url = path;
        }

        @Override
        public void run() {
            super.run();
            RTSPClient.start(url);
        }
    }

    /**
     * 播放系统拍照声音
     */
    private MediaPlayer shootMP;

    public void shootSound() {
        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        int volume = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
        if (volume != 0) {
            if (shootMP == null) {
                shootMP = MediaPlayer.create(mContext, Uri.parse("file:///system/media/audio/ui/camera_click.ogg"));
            }
            if (shootMP != null) {
                shootMP.start();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constants.START_CODE) {
            String shot = data.getStringExtra(Constants.RESULT_KEY);
            if (shot.equals(Constants.RESULT_VALUE)) {
                linearLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RTSPClient.stop();
        VideoUtils.LocalShow.removeView();
        h264FileStorePresenter.stopThreadAndClearQueue();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            /**对于好多应用，会在程序中杀死 进程，这样会导致我们统计不到此时Activity结束的信息，
             对于这种情况需要调用 'MobclickAgent.onKillProcess( Context )'
             方法，保存一些页面调用的数据。正常的应用是不需要调用此方法的。*/
            MobclickAgent.onKillProcess(mContext);
            int pid = android.os.Process.myPid();
            android.os.Process.killProcess(pid);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
